using B.S.Medical.Api.Read.Application.Command.Payment;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.Domain.Department;
using B.S.Medical.Domain.Medical;
using B.S.Medical.Domain.Payment;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Payment
{
    /// <summary>
    /// 查询支付成功详情处理器
    /// </summary>
    public class GetPaymentSuccessDetailHandler : IRequestHandler<GetPaymentSuccessDetailCommand, ApiResult<PaymentSuccessDetailDto>>
    {
        private readonly IBaseRepository<PaymentRecordModel> _paymentRecordRepository;
        private readonly IBaseRepository<DrugModel> _drugRepository;
        private readonly IBaseRepository<PatientModel> _patientRepository;
        private readonly IBaseRepository<PatientBalance> _patientBalanceRepository;
        private readonly IBaseRepository<DoctorModel> _doctorRepository;
        private readonly IBaseRepository<ManageModel> _departmentRepository;
        private readonly ILogger<GetPaymentSuccessDetailHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GetPaymentSuccessDetailHandler(
            IBaseRepository<PaymentRecordModel> paymentRecordRepository,
            IBaseRepository<DrugModel> drugRepository,
            IBaseRepository<PatientModel> patientRepository,
            IBaseRepository<PatientBalance> patientBalanceRepository,
            IBaseRepository<DoctorModel> doctorRepository,
            IBaseRepository<ManageModel> departmentRepository,
            ILogger<GetPaymentSuccessDetailHandler> logger)
        {
            _paymentRecordRepository = paymentRecordRepository;
            _drugRepository = drugRepository;
            _patientRepository = patientRepository;
            _patientBalanceRepository = patientBalanceRepository;
            _doctorRepository = doctorRepository;
            _departmentRepository = departmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理查询支付成功详情命令
        /// </summary>
        public async Task<ApiResult<PaymentSuccessDetailDto>> Handle(GetPaymentSuccessDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation($"开始查询支付成功详情，PaymentId: {request.PaymentId}, OrderNo: {request.OrderNo}");

                // 查询支付记录
                PaymentRecordModel paymentRecord;
                
                if (request.PaymentId > 0)
                {
                    paymentRecord = _paymentRecordRepository.GetAll()
                        .Where(p => p.Id == request.PaymentId && !p.IsDeleted)
                        .FirstOrDefault();
                }
                else if (!string.IsNullOrEmpty(request.OrderNo))
                {
                    paymentRecord = _paymentRecordRepository.GetAll()
                        .Where(p => p.OrderNo == request.OrderNo && !p.IsDeleted)
                        .FirstOrDefault();
                }
                else
                {
                    return new ApiResult<PaymentSuccessDetailDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "请提供支付记录ID或订单号"
                    };
                }

                if (paymentRecord == null)
                {
                    _logger.LogWarning($"未找到支付记录，PaymentId: {request.PaymentId}, OrderNo: {request.OrderNo}");
                    return new ApiResult<PaymentSuccessDetailDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到指定支付记录"
                    };
                }

                // 查询患者信息
                var patient = _patientRepository.GetAll()
                    .Where(p => p.Id == paymentRecord.PatientId && !p.IsDeleted)
                    .FirstOrDefault();

                if (patient == null)
                {
                    _logger.LogWarning($"未找到ID为 {paymentRecord.PatientId} 的患者");
                    return new ApiResult<PaymentSuccessDetailDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到患者信息"
                    };
                }

                // 查询医生信息
                var doctor = _doctorRepository.GetAll()
                    .Where(d => d.Id == paymentRecord.DoctorId && !d.IsDeleted)
                    .FirstOrDefault();

                // 查询科室信息
                var department = doctor != null ? 
                    _departmentRepository.GetAll()
                        .Where(d => d.Id == doctor.DepartmentId && !d.IsDeleted)
                        .FirstOrDefault() : null;

                // 查询患者余额
                var balance = _patientBalanceRepository.GetAll()
                    .Where(b => b.PatientId == paymentRecord.PatientId && !b.IsDeleted)
                    .FirstOrDefault();

                decimal cardBalance = balance?.Balance ?? 0;

                // 构建返回结果
                var result = new PaymentSuccessDetailDto
                {
                    ItemName = paymentRecord.ItemName,
                    DepartmentName = department?.DepartmentName ?? string.Empty,
                    DoctorName = doctor?.DoctorName ?? string.Empty,
                    PatientName = patient.Name,
                    IdCard = patient.IdCard,
                    PaymentMethod = paymentRecord.PayType ?? "卡内余额",
                    CardBalance = cardBalance,
                    OrderAmount = paymentRecord.Amount,
                    OrderNo = paymentRecord.OrderNo ?? $"{DateTime.Now:yyyyMMddHHmmss}{paymentRecord.Id}",
                    OrderTime = paymentRecord.PayTime ?? paymentRecord.CreateTime,
                    OrderStatus = paymentRecord.IsPaid ? "已支付" : "未支付",
                    ItemDetails = new List<PaymentSuccessItemDto>()
                };

                // 根据项目名称模拟生成明细项
                if (paymentRecord.ItemName == "西药费")
                {
                    // 查询药品表，获取药品信息
                    var drugs = _drugRepository.GetAll()
                        .Where(d => !d.IsDeleted)
                        .Take(2) // 模拟获取2种药品
                        .ToList();

                    if (drugs.Any())
                    {
                        foreach (var drug in drugs)
                        {
                            int quantity = 3; // 模拟数量
                            result.ItemDetails.Add(new PaymentSuccessItemDto
                            {
                                Name = drug.DrugName,
                                UnitPrice = drug.UnitPrice,
                                Quantity = quantity,
                                Amount = drug.UnitPrice * quantity
                            });
                        }
                    }
                    else
                    {
                        // 如果没有药品数据，添加模拟数据
                        result.ItemDetails.Add(new PaymentSuccessItemDto
                        {
                            Name = "普罗布考片",
                            UnitPrice = 50.00m,
                            Quantity = 3,
                            Amount = 150.00m
                        });
                        result.ItemDetails.Add(new PaymentSuccessItemDto
                        {
                            Name = "阿司匹林肠溶片",
                            UnitPrice = 50.00m,
                            Quantity = 3,
                            Amount = 150.00m
                        });
                    }
                }
                else
                {
                    // 对于其他类型的费用，添加一个默认明细项
                    result.ItemDetails.Add(new PaymentSuccessItemDto
                    {
                        Name = paymentRecord.ItemName,
                        UnitPrice = paymentRecord.Amount,
                        Quantity = 1,
                        Amount = paymentRecord.Amount
                    });
                }

                _logger.LogInformation($"成功查询到支付成功详情，PaymentId: {request.PaymentId}, OrderNo: {request.OrderNo}");

                return new ApiResult<PaymentSuccessDetailDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询支付成功详情时发生错误，PaymentId: {request.PaymentId}, OrderNo: {request.OrderNo}");
                return new ApiResult<PaymentSuccessDetailDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"查询失败: {ex.Message}"
                };
            }
        }
    }
} 